package com.shensi.adminCollect.service.station.impl;

import com.shensi.adminCollect.common.enums.PayTypeEnum;
import com.alibaba.fastjson.JSON;
import com.shensi.common.core.domain.AjaxResult;
import com.shensi.common.core.domain.ResultData;
import com.shensi.common.redis.service.RedisCache;
import com.shensi.adminCollect.common.enums.RechargeTypeEnum;
import com.shensi.common.core.exception.CustomException;
import com.shensi.common.core.utils.MathUtil;
import com.shensi.adminCollect.enums.customer.CardRecordType;
import com.shensi.adminCollect.domain.station.*;
import com.shensi.adminCollect.domain.station.dto.CardClassSettDto;
import com.shensi.adminCollect.enums.station.PrintEnum;
import com.shensi.adminCollect.service.station.*;
import com.shensi.adminCollect.utils.station.FeiEPrinterUtil;
import com.shensi.adminCollect.utils.station.Methods;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ClassSettlementPrintServiceImpl implements ClassSettlementPrintService {


    @Resource
    private IClassSettlementService classSettlementService;

    @Resource
    private ClassSettlementCardService classSettlementCardService;

    @Resource
    private IStationService stationService;

    @Resource
    private IStationDeviceManageService stationDeviceManageService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private RestTemplate restTemplate;
    @Value("${qujia.payBaseUrl}")
    private String payBaseUrl;

    @Override
    @Async("threadPoolTaskExecutor")
    public void getPushMessage(ClassSettlement classSettlement) throws InterruptedException {
        // 防止事务未提交导致查询不到
        Thread.sleep(3000);
        ClassSettlementInfo classSettlementInfo = classSettlementService.classPushInfoByClassNo(classSettlement);
        this.feiePush(classSettlementInfo, false);

    }

    /**
     * 班结统一打印
     *
     * @param classSettlementInfo 班结信息
     * @param extraPrint          是否补打
     */
    // 打印的班结小票的排版
    public void feiePush(ClassSettlementInfo classSettlementInfo, boolean extraPrint) { //
        try {
            List<ClassSettlement> sumClassList = classSettlementInfo.getSumClassList();
            if (sumClassList == null || sumClassList.size() <= 0) {
                return;
            }
            Station station = stationService.selectStationById(sumClassList.get(0).getStationId());

            StationDeviceManage stationDeviceManage = new StationDeviceManage();
            stationDeviceManage.setStationId(sumClassList.get(0).getStationId());
            stationDeviceManage.setDeviceType("3");
            List<StationDeviceManage> stationDeviceManages = stationDeviceManageService.selectStationDeviceManageList(stationDeviceManage);
            if (stationDeviceManages == null || stationDeviceManages.size() <= 0) {
                return;
            }
            StationDeviceManage stationDevice = stationDeviceManages.get(0);
            String deviceFactory = stationDevice.getDeviceFactory();
            Map<String, Object> printInfo = getPrintInfo(classSettlementInfo, station);
            printInfo.put("printType", deviceFactory); // 打印机类型
            printInfo.put("extraPrint", extraPrint); // 是否补打
            ResultData resultData = restTemplate.postForObject(payBaseUrl + "/receiptSection/getClassSettlementReceiptString", printInfo, ResultData.class);

            if (resultData.getCode() != 0) {
                throw new CustomException(resultData.getMsg());
            }
            String receiptStr = (String) resultData.getData();
            PrintEnum printEnum = PrintEnum.getByCode(deviceFactory);
            switch (printEnum) {
                case YILIANYUNK4:
                    String audioK4 = "<VN>8</VN>";

                    String ylyContentK4 = receiptStr.replace("<BR>", "\r\n").replace("</B></BOLD>", "").replace("<BOLD><B>", "");
                    //初始化控制器类
                    Methods mK4 = Methods.getInstance();
                    Object tokenK4 = redisCache.getCacheObject("STATION:DEVICE:" + stationDevice.getClientId());

                    Integer random6K4 = (int) ((Math.random() * 9 + 1) * 100000);

                    if (Objects.nonNull(tokenK4)) {
//                        String refreshTokenK4 = mK4.getFreedomToken();
                        String printK4 = mK4.print(stationDevice.getDeviceNo(), audioK4 + ylyContentK4.toString(), random6K4.toString());
                        log.info("小票机返回值{}", printK4);
                        JSONObject json = new JSONObject(printK4);
                        if ("0".equals(json.getString("error"))) {
                            break;
                        }
                    }

                    //初始化终端信息
                    mK4.init(stationDevice.getClientId(), stationDevice.getClientSecret());
                    //获取token
                    String refreshTokenK4 = mK4.getFreedomToken();
                    //存入redis
                    redisCache.setCacheObject("STATION:DEVICE:" + stationDevice.getClientId(), refreshTokenK4, 30, TimeUnit.DAYS);


                    String printK4 = mK4.print(stationDevice.getDeviceNo(), audioK4 + ylyContentK4, random6K4.toString());
                    log.info("小票机返回值2{}", printK4);

                    break;

                case YILIANYUN:
                    String audio = "<audio>班结信息已打印</audio>";

                    String ylyContent = receiptStr.toString().replace("<BR>", "\r\n").replace("</B></BOLD>", "").replace("<BOLD><B>", "");
                    //初始化控制器类
                    Methods m = Methods.getInstance();
                    Object token = redisCache.getCacheObject("STATION:DEVICE:" + stationDevice.getClientId());

                    Integer random6 = (int) ((Math.random() * 9 + 1) * 100000);

                    if (Objects.nonNull(token)) {
                        String refreshToken = m.getFreedomToken();
                        String print = m.print(stationDevice.getDeviceNo(), audio + ylyContent.toString(), random6.toString());
                        log.info("小票机返回值{}", print);
                        JSONObject json = new JSONObject(print);
                        if ("0".equals(json.getString("error"))) {
                            break;
                        }
                    }

                    //初始化终端信息
                    m.init(stationDevice.getClientId(), stationDevice.getClientSecret());
                    //获取token
                    String refreshToken = m.getFreedomToken();
                    //存入redis
                    redisCache.setCacheObject("STATION:DEVICE:" + stationDevice.getClientId(), refreshToken, 30, TimeUnit.DAYS);


                    String print = m.print(stationDevice.getDeviceNo(), audio + ylyContent, random6.toString());
                    log.info("小票机返回值2{}", print);
                    break;
                case FEIE:
                    FeiEPrinterUtil.printReceipt(stationDeviceManages.get(0).getDeviceNo(), receiptStr);
                    break;
            }
            //修改小票打印状态
            ClassSettlement classSettlement = classSettlementInfo.getClassSettlement();
            classSettlementService.updateClassSettlementPrintStatus(classSettlement.getClassNo());

            return;
        } catch (Exception e) {
            log.error(">pushConsumeToUser", e);
            return;
        }

    }

    private Map<String, Object> getPrintInfo(ClassSettlementInfo classSettlementInfo, Station station) {
        StringBuilder content = new StringBuilder();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> baseSetting = new HashMap<>(); // 基础设置
        if (null != station) {
            baseSetting.put("stationName", station.getStationName()); //油站名称
        }
        List<ClassSettlement> sumClassList = classSettlementInfo.getSumClassList();
        Map<String, Object> totalSum = new HashMap<>(); // 合计汇总
        List collectionDetailsList = new ArrayList(); // 消费收款明细
        List rechargeSum = new ArrayList();// 充值汇总
        List oilSum = new ArrayList();// 油品汇总
        List employeeSum = new ArrayList(); // 员工汇总
        Map<String, Object> pageTail = new HashMap<>(); // 页尾

        if (true) {
            content.append("<BOLD><B>--班结小票----</B></BOLD><BR>");
            if (sumClassList.get(0).getClassStartTime() != null) {
                baseSetting.put("successioDate", sdf.format(sumClassList.get(0).getClassStartTime())); // 接班时间
            } else {
                baseSetting.put("successioDate", "首次"); // 接班时间
            }
            if (sumClassList.get(0).getClassEndTime() != null) {
                baseSetting.put("shiftDate", sdf.format(sumClassList.get(0).getClassEndTime())); // 交班时间
            }
            content.append("班结人：" + sumClassList.get(0).getCreateName() + "<BR>");
            baseSetting.put("submitter", sumClassList.get(0).getCreateName()); // 交接人


            if (CollectionUtils.isNotEmpty(sumClassList)) {
                BigDecimal receivableAmt = sumClassList.get(0).getReceivableAmt() != null ? sumClassList.get(0).getReceivableAmt() : BigDecimal.ZERO;
                totalSum.put("receivableAmt", receivableAmt); // 消费应收总金额
            }


            if (sumClassList.get(0).getDiscountAmt() != null) {
                BigDecimal discountAmountAmt = Objects.isNull(sumClassList.get(0).getDiscountAmt()) ? BigDecimal.ZERO : sumClassList.get(0).getDiscountAmt();
                BigDecimal discountCouponAmt = Objects.isNull(sumClassList.get(0).getDiscountCouponAmt()) ? BigDecimal.ZERO : sumClassList.get(0).getDiscountCouponAmt();
                totalSum.put("discountAmt", discountAmountAmt.add(discountCouponAmt));// 消费优惠总金额
            }

            if (sumClassList.get(0).getReceivableAmt() != null) {
                totalSum.put("receivedAmt", sumClassList.get(0).getAmt());// 消费实收总金额
            }
            List<ClassSettlement> refundSummary = classSettlementInfo.getRefundSummary();
            if (CollectionUtils.isNotEmpty(refundSummary)) {
                BigDecimal refundSum = refundSummary.stream().filter(m -> !"合计".equals(m.getPayType())).map(ClassSettlement::getRefundAmt).reduce(BigDecimal.ZERO, BigDecimal::add);

                //充值退款
                BigDecimal refRefoundSum = refundSummary.stream().filter(m -> !"合计".equals(m.getPayType()) && "ref".equals(m.getPayType())).map(ClassSettlement::getRefundAmt).reduce(BigDecimal.ZERO, BigDecimal::add);
                //消费退款
                BigDecimal consumeRefoundSum = refundSum.subtract(refRefoundSum);
                //充值退款
                totalSum.put("consumptionRefundAmt", consumeRefoundSum);// 消费消费退款
                totalSum.put("rechargeRefundAmt", refRefoundSum);// 充值退款
                totalSum.put("refundAmt", refundSum);// 退款总金额
            }

            //平台储值合计
//                if(!CollectionUtils.isEmpty(sumCzList)){
            BigDecimal dzkAmk = BigDecimal.ZERO;
            BigDecimal dkqAmt = BigDecimal.ZERO;
            BigDecimal cdkAmt = BigDecimal.ZERO;
            //电子卡手动充值金额
            BigDecimal handRecharge = BigDecimal.ZERO;
            List<ClassSettlementCard> transactionSummary = classSettlementInfo.getTransactionSummary();
            for (ClassSettlementCard classSettlementCard : transactionSummary) {
                if (RechargeTypeEnum.imp.getType().equals(classSettlementCard.getPayType())) {
                    handRecharge = handRecharge.add(Objects.isNull(classSettlementCard.getAmt()) ? BigDecimal.ZERO : classSettlementCard.getAmt());
                }
                if (RechargeTypeEnum.pos.getType().equals(classSettlementCard.getPayType())) {
                    handRecharge = handRecharge.add(Objects.isNull(classSettlementCard.getAmt()) ? BigDecimal.ZERO : classSettlementCard.getAmt());
                }
                if (RechargeTypeEnum.wx.getType().equals(classSettlementCard.getPayType())) {
                    handRecharge = handRecharge.add(Objects.isNull(classSettlementCard.getAmt()) ? BigDecimal.ZERO : classSettlementCard.getAmt());
                }
            }

            //车队卡储值
            BigDecimal handCdkRecharge = BigDecimal.ZERO;
            for (ClassSettlementCard classSettlementCard : transactionSummary) {
                if (RechargeTypeEnum.cdk.getType().equals(classSettlementCard.getPayType())) {
                    handCdkRecharge = Objects.isNull(classSettlementCard.getAmt()) ? BigDecimal.ZERO : classSettlementCard.getAmt();
                }
            }

            BigDecimal handDkqRecharge = BigDecimal.ZERO;
            for (ClassSettlementCard classSettlementCard : transactionSummary) {
                if (RechargeTypeEnum.dkq.getType().equals(classSettlementCard.getPayType())) {
                    handDkqRecharge = Objects.isNull(classSettlementCard.getAmt()) ? BigDecimal.ZERO : classSettlementCard.getAmt();
                }
            }
            dzkAmk = handRecharge;
            List<ClassSettlementCard> sumCzList = classSettlementInfo.getSumCzList();
            for (ClassSettlementCard classSettlementCard : sumCzList) {
                if (StringUtils.isEmpty(classSettlementCard.getRechargeType())) {
                    continue;
                }
                String des = "";
                if (!StringUtils.isEmpty(classSettlementCard.getRechargeType())) {
                    if (PayTypeEnum.dkq == PayTypeEnum.getByType(classSettlementCard.getRechargeType())) {
                        dkqAmt = classSettlementCard.getAmt();
                    } else if (PayTypeEnum.cdk == PayTypeEnum.getByType(classSettlementCard.getRechargeType())) {
                        cdkAmt = classSettlementCard.getAmt();
                    }
                }

//                        content.append(des + "     " + classSettlementCard.getOrderCount() + "     " + classSettlementCard.getAmt() + "<BR>");

            }
            totalSum.put("dzkSavingsAtm", dzkAmk);// 电子卡储值额
            totalSum.put("hykSavingsAtm", handDkqRecharge);// 实体卡储值额
            totalSum.put("cdkSavingsAtm", handCdkRecharge);// 车队卡储值额
            totalSum.put("savingsAtm", dzkAmk.add(handDkqRecharge).add(handCdkRecharge));// 储值合计
//                }
            List<ClassSettlement> sumOilList = classSettlementInfo.getSumOilList();
            BigDecimal sumOrderCount = sumOilList.stream().filter(cs -> Objects.nonNull(cs.getOrderLiters())).map(ClassSettlement::getOrderLiters).reduce(BigDecimal.ZERO, BigDecimal::add);
            totalSum.put("salesVolume", sumOrderCount);// 销售量(L/KG)

            BigDecimal consumeReceived = Objects.isNull(sumClassList.get(0).getAmt()) ? BigDecimal.ZERO : sumClassList.get(0).getAmt();
            BigDecimal actualRechargeReceivedAmt = Objects.isNull(sumClassList.get(0).getActualRechargeReceivedAmt()) ? BigDecimal.ZERO : sumClassList.get(0).getActualRechargeReceivedAmt();

//                content.append("到账总金额：" + consumeReceived.add(actualRechargeReceivedAmt)  + "元<BR>");
            totalSum.put("arrivalAmt", sumClassList.get(0).getTotalWithdrawalAmount().setScale(2, RoundingMode.HALF_DOWN));// 到账总金额
            // 消费收款明细
            List<ClassSettlement> sumPayTypeList = classSettlementInfo.getSumPayTypeList();
            for (ClassSettlement classSettlement1 : sumPayTypeList) {
                Map<String, Object> details = new HashMap<>(); // 消费收款明细
                if (StringUtils.isEmpty(classSettlement1.getPayType())) {
                    continue;
                }
                PayTypeEnum a = PayTypeEnum.getByType(classSettlement1.getPayType());
                if (a != null) {
                    details.put("payType", a.getDes());
                } else {
                    details.put("payType", classSettlement1.getPayType());
                }
                details.put("count", padCountString(String.valueOf(classSettlement1.getOrderCount())));
                details.put("amount", classSettlement1.getAmt().setScale(2, RoundingMode.HALF_DOWN));
                collectionDetailsList.add(details);
            }

            // 充值汇总
            if (!CollectionUtils.isEmpty(transactionSummary)) {
                for (ClassSettlementCard classSettlementCard : transactionSummary) {
                    Map<String, Object> rechargeInfo = new HashMap<>();
                    if ("合计".equals(classSettlementCard.getPayType().toString()) || Objects.isNull(classSettlementCard.getAmt()) || BigDecimal.ZERO.compareTo(classSettlementCard.getAmt()) == 0) {
                        continue;
                    }
                    BigDecimal rechargeAmt = Objects.nonNull(classSettlementCard.getAmt()) ? classSettlementCard.getAmt() : BigDecimal.ZERO;
                    rechargeInfo.put("rechargeType", RechargeTypeEnum.getByType(classSettlementCard.getPayType()).getDes());
                    rechargeInfo.put("count", padCountString(classSettlementCard.getOrderCount().toString()));
                    rechargeInfo.put("amount", rechargeAmt);
                    rechargeSum.add(rechargeInfo);
                }
            }


/*                if(!CollectionUtils.isEmpty(queryGroupByRecharge)){
                for (ClassSettlementCard classSettlementCard : queryGroupByRecharge) {
                    content.append(CardRecordType.getByKey(classSettlementCard.getPayType()).getName() + "    " + padCountString(classSettlementCard.getOrderCount().toString()) + "    " + classSettlementCard.getAmt().toString() + "<BR>");
                }
            }*/


            // 油品汇总
            for (ClassSettlement classSettlement1 : sumOilList) {
                if (StringUtils.isEmpty(classSettlement1.getOilName())) {
                    continue;
                }
                Map<String, Object> oilInfo = new HashMap<>();
                oilInfo.put("oilName", padCountOilNameString(classSettlement1.getOilName()));
                oilInfo.put("count", padCountString(classSettlement1.getOrderCount().toString()));
                oilInfo.put("amount", classSettlement1.getAmt());
                oilSum.add(oilInfo);
            }

            //员工汇总
            // 根据活动分组查询统计信息
            List<Map<String, Object>> listDetail4User = classSettlementInfo.getListDetail4User();
            Map<String, List<Map<String, Object>>> oilPersonnelNameMap = listDetail4User.stream().filter(m -> !"合计".equals(m.get("oil_personnel_name"))).collect(Collectors.groupingBy((m -> (String) m.get("oil_personnel_name"))));
            for (Map.Entry<String, List<Map<String, Object>>> entry : oilPersonnelNameMap.entrySet()) {
                String oilPersonnelName = entry.getKey();
                List<Map<String, Object>> value = entry.getValue();
                //笔数
                Integer orderCount = value.stream().mapToInt(map -> ((Number) map.get("order_count")).intValue()).sum();
                //金额
                Double amt = value.stream().mapToDouble(map -> ((Number) map.get("amt")).doubleValue()).sum();

                if (StringUtils.isNotBlank(oilPersonnelName) && oilPersonnelName.length() > 5) {
                    oilPersonnelName = oilPersonnelName.substring(0, 5);
                }
                Map<String, Object> employeeInfo = new HashMap<>(); // 员工汇总
                employeeInfo.put("employeeName", padCountOilNameString(oilPersonnelName));
                employeeInfo.put("count", padCountString(orderCount.toString()));
                employeeInfo.put("amount", new BigDecimal(amt).setScale(2, RoundingMode.HALF_DOWN));
                employeeSum.add(employeeInfo);
            }


            pageTail.put("printTime", sdf.format(new Date()));
            Boolean personFlage = false;
//                if (station != null && station.getClassPersonFlag() != null && station.getClassPersonFlag().equals("1")) {
//                    for (Map<String, Object> oilPerson : oilPersonList) {
//                        content.append("<BOLD><B>-班结小票---" + oilPerson.get("oilPersonnelName") + "-</B></BOLD><BR>");
//                        if (sumClassList.get(0).getClassStartTime() != null) {
//                            content.append("开始时间：" + sdf.format(sumClassList.get(0).getClassStartTime()) + "<BR>");
//                        } else {
//                            content.append("开始时间：" + "首次" + "<BR>");
//                        }
//                        if (sumClassList.get(0).getClassEndTime() != null) {
//                            content.append("结束时间：" + sdf.format(sumClassList.get(0).getClassEndTime()) + "<BR>");
//                        }
//                        content.append("油品   笔数    升数     金额" + "<BR>");
//                        content.append("--------------------------" + "<BR>");
//                        List<ClassSettlement> oilList = (List<ClassSettlement>) oilPerson.get("oilList");
//                        for (ClassSettlement classSettlement1 : oilList) {
//                            content.append(classSettlement1.getOilName() + "   " + classSettlement1.getOrderCount() + "    " + classSettlement1.getOrderLiters() + "    " + classSettlement1.getAmt() + "<BR>");
//                        }
//                        content.append("--------------------------" + "<BR>");
//                        if (oilPerson.get("orderCount") != null) {
//                            content.append("小票张数：" + oilPerson.get("orderCount") + "<BR>");
//                        }
//
//                        if (oilPerson.get("receivableAmt") != null) {
//                            content.append("消费金额：" + oilPerson.get("receivableAmt") + "<BR>");
//                        }
//                        if (oilPerson.get("discountAmt") != null) {
//                            content.append("优惠金额：" + oilPerson.get("discountAmt") + "<BR>");
//                        }
//
//                        if (oilPerson.get("refundAmt") != null) {
//                            content.append("退款金额：" + oilPerson.get("refundAmt") + "<BR>");
//                        }
//                        if (oilPerson.get("amt") != null) {
//                            content.append("订单实际支付金额：" + oilPerson.get("amt") + "<BR>");
//                        }
//                        content.append("<BR>");
//                        content.append("<BR>");
//                    }
//                }
        }
//            content.append("<BR>");
//            content.append("<BR>");


        Map<String, Object> printInfo = new HashMap<>();
        printInfo.put("baseSetting", baseSetting); // 基础设置
        printInfo.put("totalSum", totalSum);// 汇总合计
        printInfo.put("collectionDetailsList", collectionDetailsList); // 消费收款明细
        printInfo.put("rechargeSum", rechargeSum); // 充值汇总
        printInfo.put("oilSum", oilSum); // 油品汇总
        printInfo.put("employeeSum", employeeSum); // 员工汇总
        printInfo.put("enterpriseId", station.getEnterpriseId()); // 油企id
        printInfo.put("pageTail", pageTail); // 页尾
        return printInfo;
    }

    private String padCountString(String input) {
        if (StringUtils.isEmpty(input)) {
            return input;
        }
        int length = getChineseLength(input);
        if (length >= 4) {
            return input;
        } else {
            StringBuilder paddedString = new StringBuilder(input);
            for (int i = 0; i < (4 - length); i++) {
                paddedString.append(" ");
            }
            return paddedString.toString();
        }
    }

    public static int getChineseLength(String strName) {
        char[] ch = strName.toCharArray();
        int length = 0;
        for (int i = 0; i < ch.length; i++) {
            char c = ch[i];
            if (isChinese(c)) {
                length += 2;
            } else {
                length += 1;
            }
        }
        return length;
    }

    /**
     * 判断输入的字符是否是汉字
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION;
    }

    private String padCountOilNameString(String input) {
        if (StringUtils.isEmpty(input)) {
            return input;
        }
        int length = getChineseLength(input);
        if (length >= 8) {
            return input;
        } else {
            StringBuilder paddedString = new StringBuilder(input);
            for (int i = 0; i < (8 - length); i++) {
                paddedString.append(" ");
            }
            return paddedString.toString();
        }
    }

    private CardClassSettDto countCardSett(List<ClassSettlementCard> settlementCardList) {
        Map<CardRecordType, ClassSettlementCard> map = new HashMap<>();
        // 根据payType进行分组统计
        for (ClassSettlementCard settlementCard : settlementCardList) {
            if (!StringUtils.equals("dzk", settlementCard.getRechargeType())) {
                continue;
            }
            CardRecordType payType = CardRecordType.getByKey(settlementCard.getPayType(), CardRecordType.CONSUME);
            ClassSettlementCard settlement = map.get(payType);
            if (settlement == null) {
                settlement = new ClassSettlementCard();
                settlement.setPayType(payType.getKey());
                settlement.setAmt(BigDecimal.ZERO);
                settlement.setOrderCount(0L);
                settlement.setServiceCharge(BigDecimal.ZERO);
                settlement.setGiveAmt(BigDecimal.ZERO);
                map.put(payType, settlement);
            }
            settlement.setAmt(MathUtil.add(settlement.getAmt(), settlementCard.getAmt()));
            settlement.setOrderCount(MathUtil.add(settlement.getOrderCount(), settlementCard.getOrderCount()));
            settlement.setServiceCharge(MathUtil.add(settlement.getServiceCharge(), settlementCard.getServiceCharge() == null ? null : settlementCard.getServiceCharge().setScale(2, RoundingMode.HALF_UP)));
            settlement.setGiveAmt(MathUtil.add(settlement.getGiveAmt(), settlementCard.getGiveAmt()));
        }
        CardClassSettDto settDto = new CardClassSettDto();// 每个payType数据相加的总计
        settDto.setTotalAmt(BigDecimal.ZERO);
        settDto.setTotalRechargeAmt(BigDecimal.ZERO);
        settDto.setTotalGiveAmt(BigDecimal.ZERO);
        settDto.setTotalWithdrawalAmount(BigDecimal.ZERO);
        settDto.setTotalRefundAmt(BigDecimal.ZERO);
        settDto.setTotalServiceCharge(BigDecimal.ZERO);
        ArrayList<ClassSettlementCard> settList = new ArrayList<>(); // 包含所有payType数据的列表
        // 遍历所有的payType,添加map中没有的类型，并进行总计
        for (CardRecordType value : CardRecordType.values()) {
            ClassSettlementCard settlement = map.get(value);
            if (settlement == null) {
                settlement = new ClassSettlementCard();
                settlement.setPayType(value.getKey());
                settlement.setAmt(BigDecimal.ZERO);
                settlement.setOrderCount(0L);
                settlement.setServiceCharge(BigDecimal.ZERO);
                settlement.setGiveAmt(BigDecimal.ZERO);
                settlement.setWithdrawalAmount(BigDecimal.ZERO);
            }
            settList.add(settlement);
            settDto.setTotalOrderCount((int) (settDto.getTotalOrderCount() + settlement.getOrderCount()));
            switch (value) {
//                case MANUAL_ADD:
//                    settDto.setTotalAmt(settDto.getTotalAmt().add(settlement.getAmt()));
//                    break;
//                case MANUAL_SUB:
//                    settlement.setAmt(settlement.getAmt().negate());
//                    settDto.setTotalAmt(settDto.getTotalAmt().add(settlement.getAmt()));
//                    break;
                case WX_RECHARGE:
                    settDto.setTotalAmt(settDto.getTotalAmt().add(settlement.getAmt()));
                    settDto.setTotalGiveAmt(settDto.getTotalGiveAmt().add(settlement.getGiveAmt()));
                    settlement.setWithdrawalAmount(settlement.getAmt().subtract(settlement.getServiceCharge())); // 充值提现=实收-渠道费
                    settDto.setTotalWithdrawalAmount(settDto.getTotalWithdrawalAmount().add(settlement.getWithdrawalAmount()));
                    settDto.setTotalRechargeAmt(settDto.getTotalRechargeAmt().add(settlement.getAmt()));
                    settDto.setTotalServiceCharge(settDto.getTotalServiceCharge().add(settlement.getServiceCharge()));
                    settDto.setAmt(settlement.getAmt());
                    settDto.setOrderCount(settlement.getOrderCount());
                    break;
//                case CONSUME:
//                    settlement.setAmt(settlement.getAmt().negate());
//                    settDto.setTotalAmt(settDto.getTotalAmt().add(settlement.getAmt()));
//                    break;
                case REFUND:
                    settDto.setTotalAmt(settDto.getTotalAmt().subtract(settlement.getAmt()));
                    settDto.setTotalRefundAmt(settDto.getTotalRefundAmt().add(settlement.getAmt()));
                    settDto.setTotalGiveAmt(MathUtil.subtract(settDto.getTotalGiveAmt(), settlement.getGiveAmt()));
                    settlement.setWithdrawalAmount(settlement.getServiceCharge().subtract(settlement.getAmt())); // 退款提现=-(实收-渠道费)，总提现要加上这个值
                    settDto.setTotalWithdrawalAmount(settDto.getTotalWithdrawalAmount().add(settlement.getWithdrawalAmount()));
                    settDto.setTotalServiceCharge(MathUtil.subtract(settDto.getTotalServiceCharge(), settlement.getServiceCharge()));
                    //settlement.setAmt(settlement.getAmt().negate());
                    break;
            }
        }
//        ClassSettlementCard countDto = new ClassSettlementCard();
//        countDto.setPayType("zj");
//        countDto.setAmt(settDto.getTotalAmt());
//        countDto.setOrderCount((long)settDto.getOrderCount());
//        countDto.setWithdrawalAmount(settDto.getTotalWithdrawalAmount());
//        settList.add(countDto);
        settDto.setSettlementCardList(settList);
        return settDto;
    }

    @Override
    public AjaxResult exportClassSe(ClassSettlement classSettlement) {
        ClassSettlementInfo classSettlementInfo = classSettlementService.classPushInfoByClassNo(classSettlement);
        this.feiePush(classSettlementInfo, true);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult getClassSettlementPrintInfo(ClassSettlement classSettlement) {
        log.info("getClassSettlementPrintInfo:{}", JSON.toJSONString(classSettlement));
        ClassSettlementInfo classSettlementInfo = classSettlementService.classPushInfoByClassNo(classSettlement);
        List<ClassSettlement> sumClassList = classSettlementInfo.getSumClassList();
        if (sumClassList == null || sumClassList.size() <= 0) {
            return AjaxResult.success();
        }
        Station station = stationService.selectStationById(sumClassList.get(0).getStationId());
        Map<String, Object> printInfo = getPrintInfo(classSettlementInfo, station);
        log.info("班结信息：{}", printInfo);
        return AjaxResult.success(printInfo);
    }

    @Override
    public AjaxResult getPOSClassSettlementInfo(ClassSettlement classSettlement) {
        log.info("getPOSClassSettlementInfo:{}", JSON.toJSONString(classSettlement));
        ClassSettlementInfo classSettlementInfo = classSettlementService.classPushInfoByClassNo(classSettlement);
        log.info("classSettlementInfo：{}", classSettlementInfo);
        return AjaxResult.success(classSettlementInfo);
    }
}
